<template>
  <div class="audio-container">
    <!-- 显示当前播放的录音序号 -->
    <div class="audio-info" v-if="audioUrls.length > 1">
      第 {{ currentAudioIndex + 1 }} / {{ audioUrls.length }} 段录音
    </div>
    
    <!-- 进度条区域 -->
    <div class="progress-container" @click="setProgress">
      <div class="progress-bar" :style="{ width: progressPercent + '%' }"></div>
    </div>
    
    <div class="time-display">
      <span>{{ formatTime(currentTime) }}</span>
      <span>{{ formatTime(duration) }}</span>
    </div>
    
    <!-- 控制按钮 -->
    <div class="controls">
      <button class="control-btn" @click="handlePrev" :disabled="currentAudioIndex <= 0">
        <span class="iconfont icon-shangyishou"></span>
      </button>
      <button class="control-btn play-btn" @click="togglePlay">
        <span class="iconfont" :class="isPlaying ? 'icon-zanting' : 'icon-bofang'" style="font-size: 30px;"></span>
      </button>
      <button class="control-btn" @click="handleNext" :disabled="currentAudioIndex >= audioUrls.length - 1">
        <span class="iconfont icon-xiayishou"></span>
      </button>
    </div>
    
    <el-select v-model="selectedAudioIndex" placeholder="请选择" @change="selectAudio" style="width: 200px;">
      <el-option
        v-for="(url, index) in audioUrls" :key="index"
        :label="`第${index + 1}段录音`"
        :value="index"
      />
    </el-select>

    <audio 
      ref="audioPlayer" 
      :src="currentAudioUrl" 
      @timeupdate="updateProgress" 
      @ended="handleAudioEnded"
      @loadedmetadata="handleLoadedMetadata"
      hidden
    ></audio>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';

// 接收多个录音文件URL参数
const props = defineProps({
  audioUrls: {
    type: Array,
    required: true,
    default: () => []
  },
  visible: {
    type: Boolean,
    default: false
  }
});

// emits事件
const emit = defineEmits(['update:visible']);

// 音频相关引用
const audioPlayer = ref(null);
const progressPercent = ref(0);
const currentTime = ref(0);
const duration = ref(0);
const isPlaying = ref(false);
const currentAudioIndex = ref(0); // 当前播放的音频索引
const selectedAudioIndex = ref(0); // 用于存储用户选择的音频索引
let audioContext = null;
let animationId = null;
const isAudioReady = ref(false); // 新增：标识音频是否已准备好 
const currentAudioUrl = ref('');// 获取当前播放的音频URL

watch(() => props.audioUrls, (newUrls) => {
  console.log('传入的audioUrls:', newUrls); // 确认传入的URL数组是否有效
  if (newUrls.length > 0) {
    currentAudioIndex.value = 0;
    currentAudioUrl.value = newUrls[0];
    if (audioPlayer.value) {
      audioPlayer.value.src = currentAudioUrl.value;
      // 加载完成后存储元数据（如时长），但不自动播放
      audioPlayer.value.addEventListener('loadedmetadata', () => {
        duration.value = audioPlayer.value.duration; // 更新总时长
      }, { once: true });
    }
  }
});

// 监听visible变化，重置状态
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    // 当父组件设置visible为false时，执行清理
    isPlaying.value = false;
    if (animationId) cancelAnimationFrame(animationId);
    if (audioPlayer.value) {
      audioPlayer.value.pause();
      audioPlayer.value.currentTime = 0;
    }
    currentAudioIndex.value = 0;
  } else if (newVal && props.audioUrls.length > 0){
    nextTick(() => {
      if(audioPlayer.value && !audioPlayer.value.src) {
        loadAudioSource(props.audioUrls[currentAudioIndex.value]);
      }
    })
  }
});

// 新增：专门加载音频源的函数
function loadAudioSource(url) {
  if (!audioPlayer.value) return;

  isAudioReady.value = false;
  currentAudioUrl.value = url;

  // 重置音频元素
  audioPlayer.value.src = url;
  audioPlayer.value.load();

  console.log('加载音频源:', url);
}

// 监听 currentAudioIndex 变化
watch(currentAudioIndex, (newIndex) => {
  if(props.audioUrls.length === 0) return;

  //切换前先暂停当前播放
  if(audioPlayer.value && !audioPlayer.value.paused){
    audioPlayer.value.pause();
    isPlaying.value = false;
  }
  //设置新的录音并加载
  selectedAudioIndex.value = newIndex;
  loadAudioSource(props.audioUrls[newIndex]);
});

// 格式化时间显示
function formatTime(seconds) {
  if (isNaN(seconds)) return '0:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs < 10? '0' : ''}${secs}`;
}

// 更新进度条
function updateProgress() {
  if (!audioPlayer.value) return;
  
  const { currentTime: ct, duration: d } = audioPlayer.value;
  currentTime.value = ct;
  duration.value = d || 0;
  progressPercent.value = d? (ct / d) * 100 : 0;
}

// 设置播放进度
function setProgress(e) {
  if (!audioPlayer.value ||!audioPlayer.value.duration) return;
  
  const width = e.currentTarget.clientWidth;
  const clickX = e.offsetX;
  audioPlayer.value.currentTime = (clickX / width) * audioPlayer.value.duration;
}

// "播放/暂停"的切换
function togglePlay() {
  if (!audioPlayer.value || props.audioUrls.length === 0) return;
  
  if (isPlaying.value) {
    audioPlayer.value.pause();
    isPlaying.value = false;
  } else {
    //检查音频是否已准备好
    if(audioPlayer.value.readyState >= 2){
      audioPlayer.value.play().catch(err => {
        console.error('音频播放失败:', err);
        loadAudioSource(currentAudioUrl.value);
      })
      isPlaying.value = true;      
    }
  }
  isPlaying.value = !isPlaying.value;
}

// 上一曲
function handlePrev() {
  if (currentAudioIndex.value > 0) {
    currentAudioIndex.value--;
    selectedAudioIndex.value = currentAudioIndex.value
    // 切换后自动播放
    if (!isPlaying.value) {
      togglePlay();
    }
  }
}

// 下一曲
function handleNext() {
  if (currentAudioIndex.value < props.audioUrls.length - 1) {
    currentAudioIndex.value++;
    selectedAudioIndex.value = currentAudioIndex.value
    // 切换后自动播放
    if (!isPlaying.value) {
      togglePlay();
    }
  }
}

// 音频播放结束处理
function handleAudioEnded() {
  if (currentAudioIndex.value >= props.audioUrls.length - 1) {
    isPlaying.value = false;
    if (animationId) cancelAnimationFrame(animationId);
  } else {
    currentAudioIndex.value++; // 直接增加索引，watch 会处理后续
  }
}

// 选择录音段数
function selectAudio(index){
  currentAudioIndex.value = index;
  selectedAudioIndex.value = index;
  if(!isPlaying.value){
    togglePlay();
  }
}

// 组件挂载时初始化
onMounted(() => {
  console.log('组件挂载时，audioPlayer是否存在:', audioPlayer.value); 
  // 确保音频元素正确初始化
  if(props.audioUrls.length > 0 && audioPlayer.value){
    loadAudioSource(props.audioUrls[0]);
  }
});

// 组件卸载时清理
onUnmounted(() => {
  if (animationId) cancelAnimationFrame(animationId);
  if (audioContext) {
    audioContext.close().then(() => {
      audioContext = null;
      analyser = null;
      source = null;
    });
  }
  if (audioPlayer.value) {
    audioPlayer.value.pause();
  }
});
</script>

<style scoped>
@import url("@/components/AudioPlayerDialog/icon/iconfont.css");
.audio-container {
  padding: 10px 10px;
  border-radius: 16px;
  border: 1px solid #e0e0e0;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.audio-info {
  margin-bottom: 30px; /* 增大数值可进一步拉高距离 */
  font-size: 14px;
}



.progress-container {
  width: 100%;
  height: 6px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 3px;
  margin: 10px 0;
  cursor: pointer;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(to right, rgb(64, 158, 255), rgb(44, 130, 255));
  border-radius: 3px;
  position: relative;
}

.progress-bar::after {
  content: '';
  position: absolute;
  right: -8px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  background: rgb(64, 158, 255);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.2s;
}

.progress-container:hover.progress-bar::after {
  opacity: 1;
}

.time-display {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 25px;
  margin: 20px 0 10px;
}

.control-btn {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.15);
  border: 1px solid #666;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
  color: black;
  font-size: 18px;
  border: none;
  outline: none;
}

.control-btn:hover {
  background: rgba(0, 0, 0, 0.2);
  transform: scale(1.05);
}

.control-btn.play-btn {
  width: 70px;
  height: 70px;
  background-color: rgb(52, 151, 250);
  font-size: 24px;
}

:deep(.pulse) {
  animation: pulse 2s infinite;
}
</style>